package com.heba.greenmulu.diary;

import android.os.Bundle;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.heba.Cfg;
import com.heba.adapter.QuickAdapter;
import com.heba.bean.diary.ItemDiarySearchObject;
import com.heba.bean.diary.ItemDiaryTagObject;
import com.heba.bean.user.UserObject;
import com.heba.config.CommonConfig;
import com.heba.greenmulu.BaseActivity;
import com.heba.greenmulu.R;
import com.heba.greenmulu.businesslist.BusinessHomePageActivity;
import com.heba.greenmulu.businesslist.BusinessPersonActivity;
import com.heba.helper.HttpClientHelper;
import com.heba.helper.JSONHttpHelper;
import com.heba.utils.DensityUtils;
import com.heba.utils.GlideUtil;
import com.heba.view.ClearEditTextView;
import com.heba.view.FlowLayout;
import com.loopj.android.http.RequestParams;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * 日记搜索提示页面
 * Created by jason on 2020/5/20.
 */
public class ItemDiarySearchActivity extends BaseActivity {

    private ClearEditTextView clearEditTextView;
    private TextView tv_cancel;

    /**
     * 搜索view
     */
    private View search_view;
    private TextView tv_tag;
    private FlowLayout fl_view;
    private RecyclerView recyclerView;
    private QuickAdapter searchAdapter;

    private ItemDiarySearchObject diarySearchObject;
    private List<ItemDiaryTagObject> diaryTagObjects;
    private List<UserObject> userObjects;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_diary_search);
        findViewById();
        initView();
        setupClearEditTextView();
    }

    @Override
    protected void findViewById() {
        clearEditTextView = findViewById(R.id.clearEditText);
        tv_cancel = findViewById(R.id.txt_right);
        search_view = findViewById(R.id.search_view);
        tv_tag = findViewById(R.id.tv_tag);
        fl_view = findViewById(R.id.fl_view);
        recyclerView = findViewById(R.id.rv_view);
    }

    @Override
    protected void initView() {
        diaryTagObjects = new ArrayList<>();
        userObjects = new ArrayList<>();

        searchAdapter = new QuickAdapter<UserObject>(userObjects) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.item_follow_row;
            }

            @Override
            public void convert(VH holder, UserObject data, int position) {
                holder.getView(R.id.txt_follow).setVisibility(View.INVISIBLE);
                holder.setText(R.id.txt_name, data.getAccount());
                holder.setText(R.id.txt_desc, data.getNickname());
                ImageView img_avatar = holder.getView(R.id.img_avatar);
                GlideUtil.loadImageWithPlaceHolderID(ItemDiarySearchActivity.this, data.getIcon(), img_avatar, R.drawable.icon_head_portrait);

                holder.itemView.setOnClickListener(v -> {
                    Bundle bundle = new Bundle();
                    bundle.putString(CommonConfig.SEND_USER_ID, data.getUserID());
                    if (data.getAccountType() == 0){
                        openActivity(ItemPersonHomePageActivity.class, bundle);
                    }else{
                        openActivity(BusinessPersonActivity.class, bundle);
                    }
                });
            }

        };
        LinearLayoutManager layoutManager2 = new LinearLayoutManager(this);
        layoutManager2.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager2);
        recyclerView.setAdapter(searchAdapter);
    }

    /**
     * 设置edittext
     */
    private void setupClearEditTextView() {
        clearEditTextView.setTextHint(this.getResources().getString(R.string.diary_search));

        /**
         * 搜索關鍵詞
         */
        clearEditTextView.setOnEditTextListener(new ClearEditTextView.OnEditTextListener() {
            @Override
            public void onDeleteClick() {
                resetSearchView();
            }

            @Override
            public void afterTextChanged(String text) {
                getDiarySearchListData(text);
            }

            @Override
            public void onSearchClick(String text) {
                getDiarySearchListData(text);
            }

            @Override
            public void onIntent() {

            }
        });

        tv_cancel.setOnClickListener(v -> finishActivity());
    }

    /**
     * 更新标签布局
     *
     * @param list
     */
    private void updateTagFlowView(List<ItemDiaryTagObject> list) {
        fl_view.removeAllViews();

        /**
         * 添加佈局參數
         */
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, DensityUtils.dip2px(this, 20));
        params.rightMargin = DensityUtils.dip2px(this, 5);
        params.bottomMargin = DensityUtils.dip2px(this, 5);
        for (int i = 0; i < list.size(); i++) {
            fl_view.addView(updateFlowRowView(list.get(i)), params);
        }
    }

    /**
     * 添加item佈局
     */
    private View updateFlowRowView(ItemDiaryTagObject object) {
        View view = LayoutInflater.from(this).inflate(R.layout.item_diary_search_flow_row, null);
        TextView tv_text = view.findViewById(R.id.tv_text);
//        String str = object.getContent().replace("#", "");
        tv_text.setText("\"" + object.getContent() + "\"");

        view.setOnClickListener(v -> {
            Bundle bundle = new Bundle();
            bundle.putString(CommonConfig.KEYWORD, object.getContent());
            openActivity(ItemDiaryTagSearchActivity.class, bundle);
        });

        return view;
    }

    /**
     * 获取搜索的日记标签和用户列表
     */
    private void getDiarySearchListData(String word) {
        HttpClientHelper client = new HttpClientHelper();
        client.setUseLogin(true);
        RequestParams params = new RequestParams();
        params.put("Leng", Cfg.Leng);
        params.put("Keyword", word);
        client.get(Cfg.BaseUrl + "/Diary/KeywordDiary", params,
                new JSONHttpHelper.JSONHttpResponseHandler(this) {

                    @Override
                    public void Success() {
                        // TODO Auto-generated method stub
                        super.Success();
                        diaryTagObjects.clear();
                        userObjects.clear();
                        try {
                            JSONObject object = new JSONObject(response.trim()).getJSONObject("Result");
                            diarySearchObject = new Gson().fromJson(object.toString(), ItemDiarySearchObject.class);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        /**
                         * 更新数据
                         */
                        updateSearchView(diarySearchObject);

                    }

                    public void Failure() {
                        super.Failure();
                    }

                });
    }

    /**
     * 更新页面
     *
     * @param object
     */
    private void updateSearchView(ItemDiarySearchObject object) {
        if (null != object) {
            diaryTagObjects = object.getTag();
            userObjects.addAll(userObjects.size(), object.getUser());

            updateTagFlowView(diaryTagObjects);
            searchAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 重置searchView
     */
    private void resetSearchView() {
        fl_view.removeAllViews();
        userObjects.clear();
        searchAdapter.notifyDataSetChanged();
    }
}
